<?php
/**
 * Created by PhpStorm.
 * User: 董坤鸿
 * Date: 2016/10/25
 * Time: 13:42
 */

namespace App\Services;

use App\Models\Action;
use Illuminate\Database\Eloquent\Collection;
use Route;

class ActionService
{
    /**
     * 渠道后台注册路由
     */
    public static function registerRoutes(){
            $actions = Action::all();
            $use_name = 'HomeController@index';
            foreach($actions as $action) {
                if($action->isMenu == true || $action->options == null) {
                    $uri = "/{$action->module}/{$action->uri}";
                    Route::get($uri, ['uses' => $use_name, 'as' => "$action->key"]);
                }
            }
    }

    public static function unsetReferActions(Collection $actions) {
        $refer = Action::where(['referKey' => ['$exists' => true]])
            ->pluck('referKey')
            ->all();
        $result = $actions->filter(function ($action) use ($refer) {
            if (!in_array($action->key, $refer)) {
                return $action;
            }
        });

        return $result->values();
    }

    public static function addReferActions($actions) {
        if ($actions === ['-']) {
            return $actions;
        }
        $refer = Action::where([
            'key' => ['$in' => $actions],
            'referKey' => ['$exists' => true]
        ])
            ->pluck('referKey')
            ->all();
        $refer = array_merge($actions, $refer);
        return array_unique($refer);
    }
}